import 'dart:async';
import 'dart:io';
import 'package:chatbot/manager/event_bus.dart';
import 'package:chatbot/manager/product_manager.dart';
import 'package:chatbot/model/event.dart';
import 'package:chatbot/page/creator_page.dart';
import 'package:chatbot/page/mine_page.dart';
import 'package:chatbot/page/splash_page.dart';
import 'package:chatbot/utils/share_preference.dart';
import 'package:chatbot/utils/utils.dart';
import 'package:chatbot/widget/progress/progress_dialog.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:chatbot/manager/dio_manager.dart';
import 'package:chatbot/page/chat_page.dart';
import 'package:chatbot/page/role_page.dart';
import 'package:chatbot/utils/colors.dart';
import 'package:custom_navigation_bar/custom_navigation_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_keychain/flutter_keychain.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_review/in_app_review.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:speech_to_text/speech_to_text_provider.dart';
import 'package:uuid/uuid.dart';

import 'manager/store_manager.dart';

void main() {
  WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
  init();

}
init() async {
  DioManager.instance;
  await LocalStorage.init();
  if (StoreManager.getUUID() == null) {
    var savedUUID = await FlutterKeychain.get(key: "uuid");

    if (savedUUID == null) {
      String uuid = const Uuid().v1();
      StoreManager.putUUID(uuid);
      await FlutterKeychain.put(key: "uuid", value: uuid);
    } else {
      StoreManager.putUUID(savedUUID);
    }
  }
  if (StoreManager.getUID() == null) {
    var savedUid = await FlutterKeychain.get(key: "uidV3");

    if (savedUid == null) {
      String uid = "${DateTime.now().millisecondsSinceEpoch~/1000}";
      StoreManager.putUID(uid);
      await FlutterKeychain.put(key: "uidV3", value: uid);
    } else {
      StoreManager.putUID(savedUid);
    }
  }

  runApp(const MainApp());
}

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: ChatColors.primaryColor),
        useMaterial3: true,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _currentIndex = 0;
  late IndexedStack _body;
  late List<Widget> _children;

  late StreamSubscription subscription;
  late StreamSubscription<dynamic> _subscription;
  ProgressDialog? pd;
  final SpeechToText speech = SpeechToText();
  late SpeechToTextProvider speechProvider;

  @override
  void initState() {
    //
    final Stream purchaseUpdated = InAppPurchase.instance.purchaseStream;
    _subscription = purchaseUpdated.listen((purchaseDetailsList) {
      _listenToPurchaseUpdated(purchaseDetailsList);
    }, onDone: () {
      _subscription.cancel();
    }, onError: (error) {
      // handle error here.
    });
    super.initState();
    subscription = Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult result) {
      if (result == ConnectivityResult.mobile ||
          result == ConnectivityResult.wifi) {

        ProductManager.instance.getProductList();
        registerUid();
        checkExpireVip();
      }
    });
    speechProvider = SpeechToTextProvider(speech);
    speechProvider.initialize();
    _children = [
      ChatPage(
        rolePrompt: StoreManager.getHomeRolePrompt(),
        roleName: StoreManager.getHomeRoleName(),
        roleTips: StoreManager.getHomeRoleTips(),
        type: -1,
        speech: speech,
        speechProvider: speechProvider,
      ),
      RoleTabPage(speech: speech, speechProvider: speechProvider),
      CreatorTabPage(
        speech: speech,
        speechProvider: speechProvider,
      ),
      MinePage()
    ];

  }

  checkExpireVip() async {
    if (!StoreManager.isVip()) {
      await InAppPurchase.instance.restorePurchases();
      EventManager.instance.eventBus.fire(RestoreUpdateEvent());
    }
  }

  void _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) {
    debugPrint("_listenToPurchaseUpdated!!!!");

    purchaseDetailsList.forEach((PurchaseDetails purchaseDetails) async {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        pd = ProgressDialog(context: context);
        pd!.show(
            barrierDismissible: false,
            msg: "请稍等...",
            hideValue: true,
            progressValueColor: ChatColors.primaryColor,
            closeWithDelay: 1000);
      } else {
        if (purchaseDetails.status == PurchaseStatus.error) {
          Utils.showToast("支付失败");
        } else if (purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored) {
          if (purchaseDetails.transactionDate != null) {
            if (purchaseDetails.productID ==
                ProductManager.instance.kIds.elementAt(0)) {
              // DateTime.now().millisecondsSinceEpoch
              //周订阅
              int transactionDate =
                  int.parse(purchaseDetails.transactionDate!); //毫秒
              int expireDate = transactionDate + 7 * 24 * 60 * 60 * 1000;
              if (expireDate > StoreManager.getExpireDate()) {
                StoreManager.putExpireDate(expireDate);
                StoreManager.putPurchasePrice(
                    "${ProductManager.instance.getWeekProductDetail().rawPrice}");
              }
              debugPrint("transactionDate week!!!!=$transactionDate");
            } else if (purchaseDetails.productID ==
                ProductManager.instance.kIds.elementAt(1)) {
              //月订阅
              int transactionDate =
                  int.parse(purchaseDetails.transactionDate!); //毫秒
              int expireDate = transactionDate + 31 * 24 * 60 * 60 * 1000;
              if (expireDate > StoreManager.getExpireDate()) {
                StoreManager.putExpireDate(expireDate);
                StoreManager.putPurchasePrice(
                    "${ProductManager.instance.getMonthProductDetail().rawPrice}");
              }
              debugPrint("transactionDate month!!!!=$transactionDate");
            } else if (purchaseDetails.productID ==
                ProductManager.instance.kIds.elementAt(2)) {
              //年订阅
              int transactionDate =
                  int.parse(purchaseDetails.transactionDate!); //毫秒
              int expireDate = transactionDate + 365 * 24 * 60 * 60 * 1000;
              if (expireDate > StoreManager.getExpireDate()) {
                StoreManager.putExpireDate(expireDate);
                StoreManager.putPurchasePrice(
                    "${ProductManager.instance.getYearProductDetail().rawPrice}");
              }
              debugPrint("transactionDate year!!!!=$transactionDate");
            }
          }
          if (purchaseDetails.status == PurchaseStatus.purchased) {
            pd?.update(msg: "支付成功", value: 100);
            Future.delayed(const Duration(milliseconds: 1000), () {
              EventManager.instance.eventBus.fire(PurchaseUpdateEvent());
            });
          }
          debugPrint("restored!!!!${purchaseDetails.transactionDate}");
          // StoreManager.setIsVip(true);
          // pd?.update(msg: "恢复成功", value: 100);
        } else if (purchaseDetails.status == PurchaseStatus.canceled) {
          pd?.update(msg: "支付取消", value: 100);
        } else {
          if (pd != null) {
            pd?.close();
          }
        }
        if (purchaseDetails.pendingCompletePurchase) {
          await InAppPurchase.instance.completePurchase(purchaseDetails);
        }
      }
    });
    goodComment();
  }

  goodComment() async {
    final InAppReview inAppReview = InAppReview.instance;
    if (await inAppReview.isAvailable()) {
      inAppReview.requestReview();
    }
  }
  @override
  void dispose() {
    super.dispose();
    _subscription.cancel();
    subscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    _body = IndexedStack(index: _currentIndex, children: _children);
    return Scaffold(
        body: _body,
        bottomNavigationBar: CustomNavigationBar(
          iconSize: 26.0,
          selectedColor: ChatColors.primaryColor,
          strokeColor: Colors.white,
          unSelectedColor: Color(0xff6c788a),
          backgroundColor: ChatColors.lightColor,
          items: [
            CustomNavigationBarItem(
              icon: const Icon(Icons.sports_volleyball),
            ),
            CustomNavigationBarItem(
              icon: const Icon(Icons.pending),
            ),
            CustomNavigationBarItem(
              icon: const Icon(Icons.school),
            ),
            // CustomNavigationBarItem(
            //   icon: const Icon(Icons.tips_and_updates),
            // ),
            CustomNavigationBarItem(
              icon: const Icon(Icons.person),
            ),
          ],
          currentIndex: _currentIndex,
          onTap: (index) {
            setState(() {
              _currentIndex = index;
            });
          },
        ));
  }

  void registerUid() {
    if (!StoreManager.isRegisterUid()) {
      StoreManager.setRegisterUid();
      DioManager.instance.registerUid();
    }
  }
}
